# -*- encoding: utf-8 -*-
# @File    :   response_code.py
# @Time    :   2021/07/27 11:52:25
# @Author  :   wudongmin
# @Contact :   wudongmin@xroom.net
# @version   :  1.0

from typing import Union
from fastapi import status
from fastapi.responses import JSONResponse, Response
from fastapi.encoders import jsonable_encoder
import datetime


def escaped_datetime(obj: datetime.datetime, mapping=None) -> str:
    """
    格式化时间
    """
    s = "%Y-%m-%d %H:%M:%S"
    return obj.strftime(s)


def resp_200(*, data: Union[str, dict, list] = None, message="Success") -> Response:
    return JSONResponse(status_code=status.HTTP_200_OK,
                        content=jsonable_encoder({
                            "code": 200,
                            "message": message,
                            "data": data,
                        },
                            custom_encoder={datetime.datetime: escaped_datetime}
                        ))


def resp_4001(*, data: Union[str, dict, list] = None, message="Request Validation Error") -> Response:
    return JSONResponse(status_code=status.HTTP_200_OK,
                        content=jsonable_encoder({
                            "code": 4001,
                            "message": message,
                            "data": data,
                        }))


def resp_404(*, data: Union[str, dict, list] = None, message="Object Do Not Exist") -> Response:
    return JSONResponse(status_code=status.HTTP_404_NOT_FOUND,
                        content=jsonable_encoder({
                            "code": 404,
                            "message": message,
                            "data": data,
                        }))


def resp_500(*, data: Union[str, dict, list] = None, message="Internal Server Error") -> Response:
    return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                        content=jsonable_encoder({
                            "code": 500,
                            "message": message,
                            "data": data,
                        }))


def resp_5002(*, data: Union[list, dict, str] = None, message: Union[list, dict, str] = "Request Fail") -> Response:
    return JSONResponse(status_code=status.HTTP_200_OK,
                        content=jsonable_encoder({
                            'code': 5002,
                            'data': data,
                            'message': message,
                        }))